package components.plugins.facesearch
{
	import FaceAPI.FaceAPI;
	
	import UIFree.ObjectEvent;
	import UIFree.uif_component;
	
	import classes.clt_events;
	
	import com.adobe.images.JPGEncoder;
	
	import components.clt_component;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	
	import mx.graphics.codec.JPEGEncoder;
	import mx.utils.Base64Encoder;
	
	public class clt_facesearch extends clt_component {
		public function clt_facesearch(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:String='') {
			super(parent, ax, ay, awidth, aheight, styleClass);
		}
		
		override protected function listenEvents():void {
			super.listenEvents();
		}
		
		public function execute(a_params: Object): void {
			var eventObj: Object = {
				result: null
			} 
			workspace.dispatchEvent(new ObjectEvent(clt_events.GETPHOTO, eventObj));
			if (eventObj.result) doAfterResult(eventObj.result);
		}
		
		protected function doAfterResult(bitmap: Bitmap): void {
			var fapi: FaceAPI = new FaceAPI('d45fd466-51e2-4701-8da8-04351c872236', '171e8465-f548-401d-b63b-caf0dc28df5f');
			var ba	: ByteArray = (new JPGEncoder(80)).encode(bitmap.bitmapData);
			var ba64: Base64Encoder = new Base64Encoder();
			ba64.encodeBytes(ba);
			
			workspace.dispatchEvent(new Event(GDataEvent.REQUEST));
		
			fapi.ImageRequest(ba64.toString(), 'image.jpg',  function (img_uid: String): void {
				fapi.GetImageInfo(img_uid, function(a_data: XML): void {
					workspace.dispatchEvent(new Event(GDataEvent.RESPONSE));
					
					var ba: ByteArray = new ByteArray();
					ba.writeUTF(a_data.toString());
//					saveToFile(ba);
					
					if (a_data.faces) {
						parceFaces(a_data.faces[0].FaceInfo);
					}
				});
			});
		}

		private function parceFaces(faces: XMLList): void {
			for (var i: int=0; i<faces.length(); i++) {
				//(new mu_face(layers[0], 'face')).parceFaceXML(faces[i]);
				var face: XML = faces[i];
				var rect: Rectangle = new Rectangle(face.x[0], face.y[0], face.width[0], face.height[0]);
				
				workspace.dispatchEvent(new ObjectEvent(clt_events.SETPHOTORECT, rect));
/*				
				rect.x -= rect.width / 2;
				rect.y -= rect.height / 2;
				_shape.graphics.lineStyle(1, 0xFFFF00);
				_shape.graphics.drawRect(rect.x, rect.y, rect.width, rect.height);*/
			}
		}
	}
}